﻿using NetBrick.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityExample.Common;

class UpdateListHandler : PacketHandler
{
    public UpdateListHandler()
        : base(UnityExampleClient.Instance)
    {

    }

    public override void Process(object packetData)
    {
        Client.DebugInfo("Got a player list. Contents:");

        foreach(var id in ((UpdatePacket.PlayerList)packetData).Players)
        {
            Client.DebugInfo("- {0}", id);
        }

        foreach (var id in ((UpdatePacket.PlayerList)packetData).Players)
        {
            if (!UnityExampleClient.Instance.Players.Contains(id) && id != UnityExampleClient.Instance.Id)
            {
                Client.DebugInfo("Player of id {0} has joined.", id);

                GameQueue.Instance.QueueAction(() =>
                {
                    var newPlayer = GameObject.Instantiate(Models.Instance.RemotePlayer);
                    newPlayer.name = id.ToString(); 
                    UnityExampleClient.Instance.Players.Add(id);
                    Client.DebugInfo("Player of id {0} has been added.", id);
                });
            }
        }

        foreach (var id in UnityExampleClient.Instance.Players)
        {
            if (!((UpdatePacket.PlayerList)packetData).Players.Contains(id) && id != UnityExampleClient.Instance.Id)
            {
                Client.DebugInfo("Player of id {0} has left.", id);

                GameQueue.Instance.QueueAction(() =>
                {
                    GameObject.Destroy(GameObject.Find(id.ToString()));
                    UnityExampleClient.Instance.Players.Remove(id);
                    Client.DebugInfo("Player of id {0} has been removed.", id);
                });
            }
        }
    }
}
